layui.use(['util'], function (util) {

    var
        table = util.table,//table
        form = util.form,//form
        upload = util.upload,//upload
        layer = util.layer;//layer


    var advertise = {

        constants: {
            html: {
                edit: appUrl + "/resources/js/lib/advertise/edit.html"
            },
            api: {
                uploadImage: appUrl + '/goods/uploadGoodsImage',
                edit: appUrl + "/advertise/edit",
                del: appUrl + "/advertise/del",
                add: appUrl + "/advertise/add",
                queryList: appUrl + '/advertise/queryList'
            }
        },

        init: function () {
            this.renderPage()
        },

        renderPage: function () {
            var self = this;
            //执行一个 table 实例
            table.render({
                elem: '#advertiseTable'
                , height: 600
                , url: self.constants.api.queryList//数据接口
                , method: 'post' //如果无需自定义HTTP类型，可不加该参数
                , title: '用户表'
                , page: true //开启分页
                , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
                , totalRow: true //开启合计行
                , cols: [[ //表头
                    {type: 'checkbox', fixed: 'left'}
                    , {field: 'id', title: 'ID', width: '10%', sort: true, fixed: 'left', totalRowText: '合计：'}
                    , {field: 'name', title: '类别名称', width: '20%'}
                    , {field: 'content', title: '描述', width: '20%'}
                    , {
                        fixed: 'right',
                        title: '广告图片',
                        width: '35%',
                        align: 'center',
                        templet: '<div><img src="{{d.imageUrl}}" width="100" height="100"></div>'
                    }
                    , {fixed: 'right', title: '操作', width: '10%', align: 'center', toolbar: '#advertiseTableBar'}
                ]]
            });

            //监听头工具栏事件
            table.on('toolbar(advertiseFilter)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id)
                    , data = checkStatus.data; //获取选中的数据
                switch (obj.event) {
                    case 'add':
                        self.add(obj.data || {});
                        break;
                    case 'update':
                        if (data.length === 0) {
                            layer.msg('请选择一行');
                        } else if (data.length > 1) {
                            layer.msg('只能同时编辑一个');
                        } else {
                            layer.alert('编辑 [id]：' + checkStatus.data[0].id);
                        }
                        break;
                    case 'delete':
                        if (data.length === 0) {
                            layer.msg('请选择一行');
                        } else {
                            layer.msg('删除');
                        }
                        break;
                }
            });

            //监听行工具事件
            table.on('tool(advertiseFilter)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data //获得当前行数据
                    , layEvent = obj.event; //获得 lay-event 对应的值
                if (layEvent === 'detail') {
                    layer.msg('查看操作');
                } else if (layEvent === 'del') {
                    layer.confirm('真的删除行么', function (index) {
                        obj.del(); //删除对应行（tr）的DOM结构
                        layer.close(index);
                        self.del(data);
                    });
                } else if (layEvent === 'edit') {
                    self.edit(data);
                }
            });
        },
        edit: function (data) {
            var self = this;

            util.templateProxy(self.constants.html.edit, data,
                {
                    title: '编辑类目',
                    success: function () {
                        form.val("editAdvertiseForm", data);
                        self.formVerify(form);
                        form.render();
                        self.initUpload("#AdvertisePicUrl");
                    },
                    area: ['600px', '400px'],
                    confirm: function (formData) {
                        formData.imageUrl = self.imageUrl;
                        util.post(self.constants.api.edit, formData, function (resp) {
                            if (resp && resp.success) {
                                layer.closeAll();
                                self.renderPage();
                            }
                        })
                    },
                    cancel: function () {
                        layer.closeAll();
                    }
                })
        },
        formVerify: function (form) {
            if (form) {
                form.verify({
                    name: function (value) {
                        if (!value) {
                            return '必填项'
                        }
                        if (/.{0,20}/.test(value)) {
                            return '字符长度不得超过20'
                        }
                    },
                    number: [/^[0-9]*$/, '必须输入数字啊']
                })
            }
        },
        initUpload: function (uploadId) {
            var self = this;
            upload.render({
                elem: uploadId
                , url: self.constants.api.uploadImage
                , accept: 'file' //普通文件
                , size: 200 //限制文件大小，单位 200kB
                , exts: 'jpg|png|jpeg' //只允许上传压缩文件
                , done: function (res) {
                    if (res && res.data) {
                        self.imageUrl = res.data.src || "";
                    }
                }, choose: function (obj) {
                    obj.preview(function (index, file, result) {
                        $(uploadId).find('img').attr('src', result);
                    });
                }
            });
        },
        add: function (data) {
            var self = this;
            util.templateProxy(self.constants.html.edit, {
                    name: '',
                    enabled: true
                },
                {
                    title: '添加类目',
                    success: function () {
                        form.val("editAdvertiseForm", data);
                        form.render();
                        self.initUpload("#AdvertisePicUrl");
                    },
                    area: ['600px', '400px'],
                    confirm: function (formData) {
                        util.post(self.constants.api.add, formData, function (resp) {
                            if (resp && resp.success) {
                                layer.closeAll();
                                self.renderPage();
                            }
                        })
                    },
                    cancel: function () {
                        layer.closeAll();
                    }
                })
        },
        del: function (data) {
            util.post(this.constants.api.del, {id: data.id}, function (resp) {
                layer.closeAll();
            });
        }

    };

    advertise.init();
});